<template>
  <!-- 登录
       1：定义登录接口的api方法
       2：在login.vue导入登录的api
       3:在点击提交表单验证通过后调用api
       4:调用成功
           提示一下
           跳转
           token存储起来   -->

  <div class="login">
    <!-- 表单验证
          1：van-form将表单元素包起来(表单元素值要绑定好)
          2:表单元素完成验证规则  :rules=[{required:true,message:'错误信息',trigger:'触发条件（onBlur/onChange）'},{{pattern:正则,message:'错误信息',trigger:'触发条件'}}]
          3:通过ref调用van-form内的validate方法实现验证
              van-form  ref='form'
              this.$refs.form.validate().then(验证成功).catch(验证失败)
     -->
    <van-nav-bar title="面经登录"></van-nav-bar>
    <van-form ref="form">
      <van-field
        label="用户名"
        placeholder="用户名"
        v-model="form.username"
        :rules="[
          { required: true, message: '请输入用户名', trigger: 'onChange' },
          {
            pattern: /^\w{4,12}$/,
            message: '请输入4-12位用户名',
            trigger: 'onChange'
          }
        ]"
      ></van-field>
      <van-field
        label="密码"
        placeholder="密码"
        v-model="form.password"
        type="password"
        :rules="[
          { required: true, message: '请输入密码', trigger: 'onChange' },
          {
            pattern: /^\w{6,12}$/,
            message: '请输入6-12位密码',
            trigger: 'onChange'
          }
        ]"
      ></van-field>
    </van-form>
    <div class="bottom">
      <van-button block color="#fa6d1d" @click="submit">提交</van-button>
      <p class="right">
        <router-link to="/register">注册帐号</router-link>
      </p>
    </div>
  </div>
</template>
<script>
import { userLogin } from '@/api/user.js'
import { setToken, getToken } from '@/utils/locale.js'
export default {
  data () {
    return {
      form: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    submit () {
      this.$refs.form
        .validate()
        .then(async () => {
          // console.log('验证成功')
          const res = await userLogin(this.form)
          // 提示
          this.$toast.success('登录成功')
          // 存储token
          // localStorage   setItem设置    getItem获取 removeItem删除
          // localStorage.setItem('token', res.data.token)
          setToken(res.data.token)
          // 跳转到首页
          this.$router.push('/')
          console.log('登陆接口返回值', res)
          console.log('获取token', getToken())
        })
        .catch(() => {
          // console.log('验证失败')
        })
    }
  }
}
</script>
<style lang="less" scoped>
.login {
  .bottom {
    padding: 15px 15px 0;
    .right {
      text-align: right;
    }
  }
}
</style>
